package com.undsf.ezhttp;

import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Arathi on 2017/4/6.
 */
public class EasyHttpClient extends OkHttpClient {
    public static final int SUCCESS = 0;
    public static final int FILE_EXISTS = 1;
    public static final int PATH_IS_FILE = 2;

    public static final MediaType MIME_JSON = MediaType.parse("application/json");
    public static final MediaType MIME_X_WWW_FORM_URLENCODED = MediaType.parse("application/x-www-form-urlencoded");

    public String get(String url, Map<String, String> paramMap) throws IOException {
        Request request = buildGetRequest(url, paramMap);
        Response response = newCall(request).execute();
        return response.body().string();
    }

    public String post(String url, Map<String, String> paramMap) throws IOException {
        Request request = buildPostRequest(url, paramMap);
        Response response = newCall(request).execute();
        return response.body().string();
    }

    /**
     * 构建GET请求
     * @param url
     * @param paramMap
     * @return
     */
    public Request buildGetRequest(String url, Map<String, String> paramMap) {
        String linkedUrl = url;
        if (paramMap != null && paramMap.size()>0) {
            if (url.contains("?")) {
                linkedUrl += "&";
            }
            else {
                linkedUrl += "?";
            }
            linkedUrl += linkParams(paramMap);
        }
        Request request = new Request.Builder()
                .url(linkedUrl)
                .get()
                .addHeader("cache-control", "no-cache")
                .build();
        return request;
    }

    /**
     * 构建POST请求
     * @param url
     * @param paramMap
     * @return
     */
    public Request buildPostRequest(String url, Map<String, String> paramMap) {
        String content = linkParams(paramMap);
        RequestBody body = RequestBody.create(MIME_X_WWW_FORM_URLENCODED, content);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .addHeader("cache-control", "no-cache")
                .build();
        return request;
    }

    /**
     * 将请求参数用&连接起来
     * @param paramMap
     * @return
     */
    public String linkParams(Map<String, String> paramMap) {
        List<String> paramList = new ArrayList<>();
        for (Map.Entry<String, String> paramEntry : paramMap.entrySet()) {
            paramList.add(paramEntry.getKey() + "=" + paramEntry.getValue());
        }
        return StringUtils.Join(paramList, "&");
    }

    /**
     * 下载文件
     * @param path 本地路径
     * @param url URL
     * @param filename 本地文件名（如果为null，则通过URL中的文件名决定）
     * @param overwrite 是否强行覆盖已有文件
     * @return 下载成功返回0，下载失败返回非0
     * @throws IOException
     */
    public int download(String path, String url, String filename, boolean overwrite) throws IOException {
        String outFileFullName = path + "/" + filename;
        File outFile = new File(outFileFullName);
        if (outFile.exists() && !overwrite) {
            return FILE_EXISTS;
        }

        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("cache-control", "no-cache")
                .build();
        Response response = newCall(request).execute();

        // int length = (int) response.body().contentLength();

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        else {
            if (dir.isFile()) {
                // path是个文件
                return PATH_IS_FILE;
            }
        }

        byte[] binaryContent = response.body().bytes();
        FileOutputStream outStream = new FileOutputStream(outFile);
        outStream.write(binaryContent);
        outStream.flush();
        outStream.close();

        // InputStream inStream = response.body().byteStream();
        // byte[] buffer = new byte[2048];
        // int readCounter = 0;
        // while (readCounter < length) {
        //     int readBytes = inStream.read(buffer, 0, 2048);
        //     if (readBytes <= 0) {
        //         break;
        //     }
        //     outStream.write(buffer, 0, readBytes);
        //     readCounter += readBytes;
        // }

        return 0;
    }
}
